package com.good.cm.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.good.cm.dao.UserMapper;
import com.good.cm.model.UserModel;
import com.good.cm.utils.AssertUtil;
import com.good.cm.utils.Md5Utils;
import com.good.cm.vo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {
    @Resource
    private UserMapper userMapper;

    public User getUser(String id){

        return userMapper.selectById(id);
    }

    public UserModel login(String userName,String pwd){

       return checkLoginParams(userName,pwd);
    }

    /**
     * 更新密码
     * @param userId
     * @param oldPwd
     * @param newPwd
     * @param newConfPwd
     */
    public void updatePassword(String userId,String oldPwd,String newPwd,String newConfPwd)
    {
        AssertUtil.isTrue(StringUtils.isBlank(oldPwd),"旧密码输入为空！");
        AssertUtil.isTrue(StringUtils.isBlank(newPwd),"新密码输入为空！");
        AssertUtil.isTrue(newPwd.equals(oldPwd),"新密码与旧密码不能相同！");
        AssertUtil.isTrue(!newConfPwd.equals(newPwd),"确认密码两次输入不一致！");
        User u= userMapper.selectById(userId);
        AssertUtil.isTrue(u==null,"账户不存在！");
        String md5NewPwd= Md5Utils.stringToMD5(newPwd);//加密后的新密码
        String md5OldPwd=Md5Utils.stringToMD5(oldPwd);//加密输入的密码
        System.out.println("加密后密码："+md5OldPwd);
        System.out.println("之前的密码："+u.getPassword());
        //旧密码与输入密码加密后一致
        AssertUtil.isTrue(!md5OldPwd.equals(u.getPassword()),"账户或密码错误！");
        u.setPassword(md5NewPwd);//密码改为新密码加密
        int rows= userMapper.updateById(u);
        AssertUtil.isTrue(rows<1,"密码更新失败！");
    }

    private UserModel checkLoginParams(String userName, String pwd) {
        AssertUtil.isTrue(StringUtils.isBlank(userName),"用户名不能为空！");
        AssertUtil.isTrue(StringUtils.isBlank(pwd),"用户名密码为空！");
        QueryWrapper  wrapper = new QueryWrapper();
        wrapper.eq("username", userName);
        List<User> users=  userMapper.selectList(wrapper);
        if (users!=null && !users.isEmpty())
        {
            User u=users.get(0);
            String epwd= Md5Utils.stringToMD5(pwd);
            System.out.println("加密后密码："+epwd);
            AssertUtil.isTrue(!u.getPassword().equals(epwd),"用户密码错误！");
            return buildUserInfo(u);
        }else{
            AssertUtil.isTrue(true,"用户不存在！");
        }
        return null;
    }

    private UserModel buildUserInfo(User user){
        UserModel userModel=new UserModel();
        userModel.setId(user.getId());
        userModel.setDisplayname(user.getDisplayname());
        userModel.setUsername(user.getUsername());
        return  userModel;
    }
}
